//
//  Graphics.cpp
//  Sinnca Engine v2
//
//  Created by Ryan Oldis on 6/14/11.
//  Copyright 2011 Sinnca Studios. All rights reserved.
//

#include "Graphics.h"
#include "Node.h"

graphics* graphics::_instance = NULL;

graphics* graphics::Instance()
{
	if (_instance == NULL)
	{
		_instance = new graphics();
	}
	return _instance;
}


graphics::graphics()
{
	resW = 1280;
	resH = 800;
	
	fullscreen = 0;
	//currentPers = 0;
}



void graphics::createSurface()
{
    Uint32 flags = 0;
    
    flags = SDL_OPENGL;
    if (fullscreen)
        flags |= SDL_FULLSCREEN;
    
    // Create window
    gScreen = SDL_SetVideoMode (1280, 800, 0, flags);
    if (gScreen == NULL) {
		
        fprintf (stderr, "Couldn't set 640x480 OpenGL video mode: %s\n",
                 SDL_GetError());
		SDL_Quit();
		exit(2);
	}
}

void graphics::init()
{
	
	glClearColor(0.1, 0.24, 0.4, 0);
	
	glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
	glEnable(GL_TEXTURE_2D);
	
	// enable alpha fuctions
	glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
	glEnable(GL_BLEND);
	
	
	glEnable(GL_CULL_FACE);
	
	glCullFace(GL_BACK);
	
	glEnable (GL_LIGHTING);
	glEnable (GL_LIGHT0);
	glShadeModel (GL_SMOOTH);
	
	glClearDepth(1.0);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LEQUAL);
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);

}

void graphics::reshape()
{
	
	glViewport(0, 0, resW, resH);
	
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	
	gluPerspective(45.0f, (GLdouble) resW / (GLdouble) resH, 0.1f, 500.0f);
	
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	
	
}

void graphics::axisWidget(float size)
{
	// x axis
	glColor3f(1.0f, 0.0f, 0.0f);
	
	glBegin(GL_LINES);
	
	glVertex3f(0.0f, 0.0f, 0.0f);
	glVertex3f(size, 0.0f, 0.0f);
	
	glEnd();
	
	// y axis
	glColor3f(0.0f, 1.0f, 0.0f);
	
	glBegin(GL_LINES);
	
	glVertex3f(0.0f, 0.0f, 0.0f);
	glVertex3f(0.0f, size, 0.0f);
	
	glEnd();
	
	// z axis
	glColor3f(0.0f, 0.0f, 1.0f);
	
	glBegin(GL_LINES);
	
	glVertex3f(0.0f, 0.0f, 0.0f);
	glVertex3f(0.0f, 0.0f, size);
	
	glEnd();
	
}


void graphics::render()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();
	
	//axisWidget(0.1f);
	if (tree->currentScene->pers() == 1)
	{
		tree->currentScene->render();
	}
	
	
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();
	gluOrtho2D(0, resW >> 1, resH >> 1, 0);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	
	glDisable(GL_LIGHTING); // 2D elements are not effected by lighting
	glDisable(GL_CULL_FACE); // all 2D elements are not to be culled
	
	if (tree->currentScene->pers() == 0)
	{
		tree->currentScene->render();
	}
	// gui->draw()
	//Console->draw();
		
	glEnable(GL_LIGHTING);
	glEnable(GL_CULL_FACE); // turn these back on
		
	glMatrixMode(GL_PROJECTION);
	glPopMatrix();
	glMatrixMode(GL_MODELVIEW);
	
	
	glFlush();
	
}


